package com.business.controller;

import com.business.ZkClient;
import com.business.bean.ClusterInfo;
import com.business.bean.TreeNode;
import com.business.db.DerbyConn;
import com.business.services.QueryServer;
import com.google.common.collect.Lists;
import com.jfinal.core.Controller;
import com.util.HelpMe;
import com.util.TouchJdbc;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by mengdexuan on 2017/1/15 13:23.
 */
public class IndexController extends Controller {

	private static org.slf4j.Logger log= LoggerFactory.getLogger(IndexController.class);
	private TouchJdbc touchJdbc = TouchJdbc.getInstance();
	private QueryServer queryServer = new QueryServer();
	private static Connection conn = DerbyConn.getConn();

	public void index() throws Exception{
		log.info("主页面……");

		List<ClusterInfo> clusterInfoList = queryServer.listCluster();

		getRequest().setAttribute("list",clusterInfoList);


		render("index.jsp");
	}

	//清空 ZK 连接
	public void clearConn(){
		ZkClient.clearConn();
		log.info("清空 ZK 连接！");
		renderNull();
	}

	public void addServer() throws Exception{
		String ip = getPara("ip");
		int port = getParaToInt("port");

		if (HelpMe.isNull(ip)){
			renderNull();
			return;
		}

		log.info("ip --> "+ip+"		port --> "+port);

		boolean flag = queryServer.addServer(ip, port);

		log.info("添加服务结果："+flag);

		renderNull();
	}

	public void delServer(){
		String uuid = getPara("uuid");
		try {
			touchJdbc.update(conn,"delete from server_info where uuid = '"+uuid+"'");
		} catch (SQLException e) {
			e.printStackTrace();
		}
		renderNull();
	}


	public void data() throws Exception{

		String clusterId = getPara("clusterId");
		log.info("clusterId --> "+clusterId);

		TreeNode node = queryServer.getNode(clusterId);

		renderJson(new TreeNode[]{node});
	}


	public void delAllNode() throws Exception{
		String clusterId = getPara("clusterId");
		log.info("clusterId --> "+clusterId);

		queryServer.deleteAllNode(clusterId,"/");
		renderNull();
	}

	public void toManager(){
		render("manager.jsp");
	}


	public void clusterData(){

		List<Map<String, Object>> mapList = queryServer.clusterData();
		mapList = HelpMe.swapMapKeyCase(mapList);

		if (HelpMe.isNull(mapList)){
			renderJson(new ArrayList<Map<String, Object>>());
			return;
		}

		renderJson(mapList);
	}


	public void getData() throws Exception{
		String uuid = getPara("uuid");
		int type = getParaToInt("type");

		Map<String, Object> map = queryServer.getData(type, uuid);

		renderJson(map);
	}


	public void serverData(){

		List<Map<String, Object>> mapList = queryServer.serverData();
		mapList = HelpMe.swapMapKeyCase(mapList);

		if (HelpMe.isNull(mapList)){
			renderJson(new ArrayList<Map<String, Object>>());
			return;
		}

		renderJson(mapList);
	}



	public void addOrEditData() throws Exception{
		int flag = getParaToInt("flag");
		boolean isAdd = getParaToBoolean("isAdd");
		if (flag==1){
			String uuid = null;
			if (!isAdd){
				uuid = getPara("uuid");
			}
			String name = getPara("name");
			if (HelpMe.isNull(name)){
				renderNull();
				return;
			}
			queryServer.addData(name,uuid);
		}else if (flag==2){
			String ip = getPara("ip");
			Integer port = getParaToInt("port");
			String cluster = getPara("cluster");
			String uuid = null;
			if (!isAdd){
				uuid = getPara("uuid");
			}
			if (HelpMe.isNull(ip)||port==null){
				renderNull();
				return;
			}
			queryServer.addData(ip,port,cluster,uuid);
		}

		renderNull();
	}




	public void delData() throws Exception{
		int flag = getParaToInt("flag");
		String uuid = getPara("uuid");

		boolean success = queryServer.delData(flag,uuid);

		renderText(success+"");
	}



	public void getServerByClusterId(){
		String uuid = getPara("uuid");
		List<Map<String, Object>> mapList = queryServer.getServerByClusterId(uuid);

		mapList = HelpMe.swapMapKeyCase(mapList);

		if (HelpMe.isNull(mapList)){
			renderJson(new ArrayList<>());
			return;
		}

		//每 3 个切分成一个单独的 List
		List<List<Map<String, Object>>> result = Lists.partition(mapList, 3);

		renderJson(result);
	}







	//=========================================   以下是 ZK 节点操作方法 ===============================================

	//创建 ZK 节点
	public void addZkNode()throws Exception{
		String clusterId = getPara("clusterId");
		String path = getPara("path");
		String pathVal = getPara("pathVal");
		ZooKeeper zooKeeper = ZkClient.getZk(clusterId);
		if (HelpMe.isNull(pathVal)){
			zooKeeper.create(path, null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
		}else {
			zooKeeper.create(path, pathVal.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
		}
		log.info("创建 ZK 节点：path --> "+path+"	val --> "+pathVal);
		renderNull();
	}



	//查询 ZK 节点数据
	public void getZkNodeData()throws Exception{
		String clusterId = getPara("clusterId");
		String path = getPara("path");
		ZooKeeper zooKeeper = ZkClient.getZk(clusterId);
		byte[] data = zooKeeper.getData(path, false, null);
		if (data!=null){
			String val = new String(data);
			renderText(val);
		}else {
			renderText("");
		}
	}


	//删除 ZK 节点
	public void delZkNode()throws Exception{
		String clusterId = getPara("clusterId");
		String path = getPara("path");
		ZooKeeper zooKeeper = ZkClient.getZk(clusterId);
		zooKeeper.delete(path, -1);
		log.info("删除 ZK 节点：path --> "+path);
		renderNull();
	}


	//更新 ZK 节点数据
	public void updateZkNode()throws Exception{
		String clusterId = getPara("clusterId");
		String path = getPara("path");
		String pathVal = getPara("pathVal");
		ZooKeeper zooKeeper = ZkClient.getZk(clusterId);
		if (HelpMe.isNull(pathVal)){
			zooKeeper.setData(path,null,-1);
		}else {
			zooKeeper.setData(path,pathVal.getBytes(),-1);
		}
		log.info("更新 ZK 节点数据：path --> "+path+"		val --> "+pathVal);
		renderNull();
	}




}
